package com.aloda.controller.user;

import com.aloda.annotation.LoginLogAnno;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.UserEditDTO;
import com.aloda.dto.UserLoginDTO;
import com.aloda.dto.UserRegisterDTO;
import com.aloda.result.Result;
import com.aloda.service.UserService;
import com.aloda.utils.EncryptionUtil;
import com.aloda.vo.UserInfoVO;
import com.aloda.vo.UserLoginVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;

/**
 * UserController
 * @author aloda
 * @date 2024/12/19
 */
@Slf4j
@RequestMapping("/user/user")
@RestController("user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 通过手机号进行注册
     * @param userRegisterDTO
     * @return
     * @throws Exception
     */
    @PostMapping("/register")
    public Result registerByPhone(@RequestBody UserRegisterDTO userRegisterDTO) throws Exception {
        log.info("用户注册：{}",userRegisterDTO);
        String decrypt = EncryptionUtil.decrypt(userRegisterDTO.getUserPassword());
        userRegisterDTO.setUserPassword(decrypt);
        userService.registerByPhone(userRegisterDTO);
        return Result.success();
    }


    /**
     * 通过账号登录
     * @param userLoginDTO
     * @return
     * @throws Exception
     */
    @LoginLogAnno(desc = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> loginByAccount(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        log.info("用户登录：{}",userLoginDTO);
        String decrypt = EncryptionUtil.decrypt(userLoginDTO.getUserPassword());
        userLoginDTO.setUserPassword(decrypt);
        UserLoginVO userLoginVO = userService.loginByAccount(userLoginDTO);
        return Result.success(userLoginVO);
    }

    /**
     * 用户退出
     * @return
     */
    @PostMapping("/logout")
    public Result userLogout(HttpServletRequest request) {
        log.info("用户退出：{}", UserBaseContext.getUser());
        userService.userLogout(request);
        return Result.success();
    }

    /**
     * 通过token获取用户信息
     * @return
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfoByToken() {
        UserInfoVO userInfoVO = userService.getUserInfoByToken();
        return Result.success(userInfoVO);
    }

    /**
     * 用户编辑个人信息
     * @param userEditDTO
     * @return
     */
    @PutMapping
    public Result editUserInfo(@RequestBody UserEditDTO userEditDTO) {
        userService.editUserInfo(userEditDTO);
        return Result.success();
    }
}
